package com.ruoyi.mstore.listener;

import com.rabbitmq.client.Channel;
import com.ruoyi.mstore.domain.RescueRequest;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

// 消费者监听器（商家端）
@Component

public class MerchantListener {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queues = {"rescue.queue.1km", "rescue.queue.2km", "rescue.queue.3km"})
    public void handleRescueRequest(RescueRequest request, Channel channel,
                                    @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            // 使用Redis原子操作保证抢单唯一性
            Boolean acquired = redisTemplate.opsForValue().setIfAbsent(
                    "rescue:order:" + request.getOrderId(),
                    "processing",
                    10, TimeUnit.SECONDS
            );

            if (acquired != null && acquired) {
                // 业务处理逻辑（抢单成功）
                processRescueOrder(request);

                // 通知用户接单成功
                notifyUser(request);

                channel.basicAck(tag, false);
            } else {
                // 其他商家已接单，拒绝消息
                channel.basicReject(tag, false);
            }
        } catch (Exception e) {
            // 处理失败，拒绝消息（不重新入队）
            channel.basicReject(tag, false);
        }
    }

    private void processRescueOrder(RescueRequest request) {
        // 实现抢单业务逻辑
    }

    private void notifyUser(RescueRequest request) {
        // 实现用户通知逻辑
    }
}